#include "stdafx.h"
#include <string>
#include "net_module_imp.h"
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include "session_imp.h"
#include "connector_impl.h"
#include "listener_imp.h"

namespace utility
{
namespace network
{
    net_module_imp::net_module_imp()
    {

    }

    net_module_imp::~net_module_imp()
    {

        for_each(listeners_.begin(), listeners_.end(), boost::bind(&listener_imp::release, _1));

        for_each(connectors_.begin(), connectors_.end(), boost::bind(&connector_impl::release, _1));
    }

    listener * net_module_imp::create_listener()
    {
        listener_imp * l = new listener_imp(io_service);
        listeners_.insert(l);
        return l;
    }

    connector * net_module_imp::create_connector()
    {
        connector_impl * c = new connector_impl(io_service);
        connectors_.insert(c);
        return c;
    }

    uint32 net_module_imp::run()
    {
        return io_service.poll();
    }

    void net_module_imp::uninitialize()
    {
        io_service.reset();
    }

    void net_module_imp::release()
    {
        //io_service.stop();
        delete instance_;
        instance_ = NULL;
    }
    net_module_imp * net_module_imp::instance_ = NULL;
    net_module_imp * net_module_imp::instance()
    {
        if (instance_ == NULL)
            instance_ = new net_module_imp;
        return instance_;
    }

    void net_module_imp::destroy( listener_imp * l)
    {
        listeners_.erase(l);
        l->release();
    }

    void net_module_imp::destroy( connector_impl * c)
    {
        connectors_.erase(c);
        c->release();
    }

}
}

utility::network::net_module * get_net_module()
{
    return utility::network::net_module_imp::instance();
}

void destroy_net_module()
{
    dynamic_cast<utility::network::net_module_imp *>(utility::network::net_module_imp::instance())->release();
}